package com.lhuc.config.shiro;

import com.lhuc.pojo.User;
import com.lhuc.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;

import javax.annotation.Resource;

/**
 * @author lhucstart
 * @create 2021-05-29 20:14
 */
//自定义UserRealm extends AuthorizingRealm
public class UserRealm extends AuthorizingRealm {

    @Resource
    UserService userService;


    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("执行了授权");

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //info.addStringPermission("user:add");

        //拿到当前登录的对象
        Subject subject = SecurityUtils.getSubject();
        User currentUser = (User) subject.getPrincipal(); //拿到user对象

        info.addStringPermission(currentUser.getPerms());

        return info;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("执行了认证");

        UsernamePasswordToken userToken = (UsernamePasswordToken) token;

        /*
        //用户名、密码  模拟从数据库中获取
        String name = "root";
        String password = "1111";

        if (!userToken.getUsername().equals(name)){
            return null; //抛出异常 UnknownAccountException
        }

        //密码认证，shiro做~
        return new SimpleAuthenticationInfo("",password,"");
        */

        //连接真实数据库
        User user = userService.queryUserByName(userToken.getUsername());
        if (user==null){ //没有这个人
            return null; //抛出异常 UnknownAccountException
        }
        Subject currentSubject = SecurityUtils.getSubject();
        Session session = currentSubject.getSession();
        session.setAttribute("loginUser",user);

        //可以加密： MD5加密   MD5盐值加密
        //密码认证，shiro做~
        return new SimpleAuthenticationInfo(user,user.getPwd(),"");

    }
}
